<template>
  <div class="container">
    <div class="app-container">
      <div class="role-operate">
        <!-- 按钮 -->
        <el-button type="primary" size="mini" @click="showDialog = true">添加角色</el-button>
        <!-- 表格 el-table -->
        <el-table :data="roleList">
          <el-table-column prop="name" align="center" width="200" label="角色">
            <template #default="{ row }">
              <!-- row 行的数据  -->
              <!-- row.isEdit  true 编辑状态 / false 非编辑状态 -->
              <el-input v-if="row.isEdit" v-model="row.rowEdit.name" size="mini" />
              <span v-else>{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="state" align="center" width="200" label="启用">
            <template #default="{ row }">
              <!-- 已启用 未启用 -->
              <!-- state 1 0   -1 '' -->
              <el-switch v-if="row.isEdit" v-model="row.rowEdit.state" :active-value="1" :inactive-value="0" />
              <span v-else>
                {{ row.state === 1 ? '已启用' : row.state === 0 ? '未启用': '无' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="description" align="center" label="描述">
            <template #default="{ row }">
              <el-input v-if="row.isEdit" v-model="row.rowEdit.description" size="mini" type="textarea" />
              <span v-else>{{ row.description }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template #default="{ row }">
              <!-- 空标签, 当前template被解析之后, 不会显示任何的节点 -->
              <!-- <template></template> -->
              <template v-if="row.isEdit">
                <el-button size="mini" type="primary" @click="confirmEdit(row)">确定</el-button>
                <el-button size="mini" @click="row.isEdit = false">取消</el-button>
              </template>
              <template v-else>
                <el-button type="text" size="mini" @click="btnPermission(row.id)">分配权限</el-button>
                <el-button type="text" size="mini" @click="edit(row)">编辑</el-button>
                <el-button type="text" size="mini">删除</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 el-pagination -->
        <el-row type="flex" style="height: 60px" align="middle" justify="end">
          <el-pagination
            :current-page="pageParams.page"
            :page-size="pageParams.pagesize"
            :total="total"
            layout="prev, pager, next"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </div>
    </div>
    <!-- 新增角色弹出层 -->
    <el-dialog
      width="500px"
      title="新增角色"
      :visible.sync="showDialog"
      @close="btnCancel"
    >
      <!-- 表单内容 -->
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="roleForm.name" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item label="启用">
          <!-- 如果不需要校验 就不需要写 prop属性 -->
          <el-switch
            v-model="roleForm.state"
            :active-value="1"
            :inactive-value="0"
            size="mini"
          />
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="btnOK">确认</el-button>
              <el-button size="mini" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配权限弹出层 -->
    <el-dialog
      title="分配权限"
      :visible.sync="showPermissionDialog"
    >
      <el-tree
        ref="permTree"
        node-key="id"
        check-strictly
        show-checkbox
        :default-checked-keys="permIds"
        :data="permissionList"
        :props="defaultProps"
        default-expand-all
      />
      <template #footer>
        <el-row type="flex" justify="center">
          <el-col :span="6">
            <el-button size="mini" type="primary" @click="btnPermissionOk">确定</el-button>
            <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
          </el-col>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleList, addRole, assignPrem, updateRole, getRoleDetail } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { translateListToTreeData } from '@/utils'
export default {
  name: 'Role123',
  data() {
    return {
      showPermissionDialog: false, // 权限弹出
      permissionList: [],
      permIds: [], // 角色拥有的权限集合
      currentRoleId: null, // 角色id
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      roleForm: {
        name: '',
        description: '',
        state: 0 // 默认未1启用 关闭 0 打开1
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      showDialog: false,
      roleList: [],
      pageParams: {
        page: 1, // 当前的页码
        pagesize: 5 // 每页5条
      },
      total: 0
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async btnPermissionOk() {
      const permIds = this.$refs.permTree.getCheckedKeys()
      await assignPrem({ id: this.currentRoleId, permIds })
      this.$message.success('分配权限成功')
      this.showPermissionDialog = false
    },
    async btnPermission(id) {
      this.permIds = []
      this.currentRoleId = id
      // 1. 获取权限列表数据
      const res = await getPermissionList()
      this.permissionList = translateListToTreeData(res, 0)
      // 2. 根据角色id获取角色详情 - 包含了角色对应的权限集合
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      // 3. 显示弹出层
      this.showPermissionDialog = true
    },
    async confirmEdit(row) {
      // 1. 判断表单的值是否为空
      if (row.rowEdit.name && row.rowEdit.description) {
        // 2. 发送请求 - 更新数据
        await updateRole({ ...row.rowEdit, id: row.id })
        // 3. 更新显示数据
        // row.name = row.rowEdit.name // eslint校验工具 误判
        // Object.assign(目标对象, 源对象1, 源对象2, ...)
        Object.assign(row, {
          ...row.rowEdit,
          isEdit: false
        })
        // 4. 退出编辑状态 isEdit ---> false
      } else {
        this.$message.warning('角色和描述不能为空')
      }
    },
    // 行编辑
    edit(row) {
      console.log(row)
      row.isEdit = true // 进入到了编辑状态
      // 更新缓存数据
      row.rowEdit = {
        name: row.name,
        state: row.state,
        description: row.description
      }
    },
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams)
      this.total = total
      this.roleList = rows
      this.roleList.forEach(item => {
        // Object.defineProperty
        // vue中动态添加的属性 不具备响应式的能力
        // 响应式: 数据变化 - 视图自动更新
        // 如何动态的往对象中添加属性, 且还具备响应式能力?????
        // this.$set(目标对象, 属性, 属性值)
        // item.isEdit = false // isEdit 是否进入编辑状态 默认是false
        this.$set(item, 'isEdit', false)
        this.$set(item, 'rowEdit', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    handleCurrentChange(val) {
      // val当前点击的页码
      this.pageParams.page = val
      this.getRoleList()
    },
    // 添加角色 - 确认按钮
    async btnOK() {
      await this.$refs.roleForm.validate()
      await addRole(this.roleForm)
      this.$message.success('新增角色成功')
      this.getRoleList()
      this.btnCancel()
    },
    // 添加角色 - 取消按钮
    btnCancel() {
      this.$refs.roleForm.resetFields() // 重置表单数据
      this.showDialog = false // 关闭弹层
    }
  }
}
</script>
<style scoped>
.role-operate {
  padding: 10px;
}
</style>
